package com.geek.novel.services

import android.graphics.Bitmap
import com.geek.novel.common.Constant
import com.geek.novel.network.HttpResult
import com.geek.novel.network.RslHandler
import com.geek.novel.utils.CommUtil
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.google.gson.JsonObject
import io.reactivex.Observable
import okhttp3.ResponseBody

/**
 * 基础服务类
 */
open class BaseService(private val rslHandler: RslHandler) {

    open fun compose(observer: Observable<JsonObject>, key: Int){
        this.compose(observer, key, Any::class.java)
    }


    /**
     * 统一处理返回结果
     */

    /**
     * 处理返回结果
     */
    open fun <T> compose(observer: Observable<JsonObject>, key: Int, cls: Class<T>, type: Int = Constant.HTTP_RESULT_TYPE_JSON){
        observer.compose(CommUtil.compose()).subscribe(
            object : HttpResult<T, JsonObject>(cls, type) {
                override fun handleLogout() {
                    rslHandler.logout(key)
                }
                override fun handleSuccess(result: ApiResult) {
                    rslHandler.onSuccess(result, key)
                }
                override fun handleError(err: ApiErrorResult) {
                    rslHandler.onError(key, err)
					LogCatUtil.e("Global", "数据加载出错：${err.message}，key： $key")
                    ToastUtils.toastLong("服务器异常：${err.message}")
                }
            }
        )
    }


    /**
     * 处理下载文件监听
     */
    open fun composeFile(observer: Observable<ResponseBody>, key: Int){
        observer.compose(CommUtil.compose()).subscribe(
            object : HttpResult<Bitmap, ResponseBody>(Bitmap::class.java, Constant.HTTP_RESULT_TYPE_IMAGE) {
                override fun handleLogout() {
                    rslHandler.logout(key)
                }
                override fun handleSuccess(result: ApiResult) {
                    rslHandler.onSuccess(result, key)
                }
                override fun handleError(err: ApiErrorResult) {
                    rslHandler.onError(key, err)
                    ToastUtils.toast("${err.message}")
                }
            }
        )
    }

}